import { Op } from 'sequelize';
import BaseController from '../../core/baseController';

export default class CartController extends BaseController {

  constructor(ctx) {
    super(ctx)
    this.service = ctx.service.wx.search;
    this.modelPrefix = 'search'
  }

  async list() {
    const { user_id } = this.ctx.validateReq(`${this.modelPrefix}.list`).query;

    const hot = await this.ctx.service.goods.keywords.findAll({ is_show: 1 }, ['keyword', 'is_hot']);
    const history = await this.service.findAll({ user_id });

    this.ctx.success({
      data: { hot, history }
    });
  }


  /**
   * 搜索列表
   */
  async searchKey() {
    const { query: { keyword } } = this.ctx.validateReq(`${this.modelPrefix}.list`);
    const where = {};

    // if (user_id) Object.assign(where, { user_id });
    if (keyword) Object.assign(where, {
      keyword: {
        [Op.like]: `%${keyword}%`,
      }
    });

    // 历史搜索
    // const isExist = await this.service.model.findOne({
    //   where: { keyword, user_id }
    // });
    // if (!isExist) {
    //   await this.service.model.create({ keyword, user_id });
    // }
    const list = await this.ctx.service.goods.keywords.findAll(where, ['keyword']);
    this.ctx.success({
      data: list,
    });
  }



  /**
   * 搜索商品
   */
  async searchGoods() {
    const { query: { keyword, user_id } } = this.ctx.validateReq(`${this.modelPrefix}.key`);
    const where = {};

    if (keyword) Object.assign(where, {
      name: {
        [Op.like]: `%${keyword}%`,
      }
    });

    // 历史搜索
    const isExist = await this.service.model.findOne({
      where: { keyword }
    });
    if (!isExist) {
      await this.service.model.create({ keyword, user_id });
    }
    const list = await this.ctx.service.goods.main
      .findAll(where, ['name', 'nick', 'brief', 'desc', 'stock', 'price',
        'main_pic', 'market_price', 'id']);

    this.ctx.success({
      data: list,
    });
  }

  /**
   * 添加购物车
   */
  async create() {
    const { body } = this.ctx.validateReq('search.create');
    const isExist = await this.ctx.model.SearchHistory.findOne({
      where: body
    });
    if (!isExist) {
      const result = await this.ctx.service.wx.search.create(body);
      this.ctx.success({
        data: {
          id: result.id,
        },
      });
      return;
    }
    this.ctx.success();
  }


  async destroy() {
    const { params: { user_id } } = this.ctx.validateReq('search.destroy');

    const result = await this.ctx.model.SearchHistory.destroy({ where: { user_id } });
    if (result) {
      this.ctx.success({
        data: {},
        status: 201,
      });
    }
  }
}
